package com.dopdxd.combase.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.viewbinding.ViewBinding
import java.lang.reflect.Field

/**
 * @Description: Fragment基类
 * @Author: kim
 * @CreateDate: 2024/4/8 10:29
 * @Version: 1.0
 */
abstract class BaseDialogFragment<VB : ViewBinding>(private val inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB) : DialogFragment() {

    private var _binding: VB? = null
    val mBinding: VB get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflater(inflater, container, false)
        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(savedInstanceState)
        initListener()
    }

    override fun onStart() {
        super.onStart()
        try {
            val window = dialog!!.window
            window!!.setLayout(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun show(fragmentManager: FragmentManager, tag: String?) {
        if (!fragmentManager.isDestroyed && !isAdded) {
            showAllowingStateLoss(fragmentManager, tag)
        }
    }


    override fun dismiss() {
        dismissAllowingStateLoss()
    }


    open fun showAllowingStateLoss(manager: FragmentManager, tag: String?) {
        try {
            val dismissed: Field = DialogFragment::class.java.getDeclaredField("mDismissed")
            dismissed.isAccessible = true
            dismissed.set(this, false)
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        try {
            val shown: Field = DialogFragment::class.java.getDeclaredField("mShownByMe")
            shown.isAccessible = true
            shown.set(this, true)
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        val ft: FragmentTransaction = manager.beginTransaction()
        if(!isAdded){
            ft.add(this, tag)
        }
        ft.commitAllowingStateLoss()
    }

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initListener()

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}